package com.min.main.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.min.common.entity.QueryPage;
import com.min.common.entity.R;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.min.main.entity.DictEntity;
import com.min.main.dao.DictDao;

import java.sql.Wrapper;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 字典表
 *
 * @author fengt
 * @date 2021-07-30
 */
@Service
public class DictService extends ServiceImpl<DictDao, DictEntity> {

    public R getRoots() {
        final List<DictEntity> roots = this.list(Wrappers.lambdaQuery(DictEntity.class).eq(DictEntity::getParentId, 0L));
        return R.ok().put("roots", roots);
    }

    public R tree(QueryPage<DictEntity> page) {
        page.getQuery().setParentId(0L);
        QueryPage<DictEntity> pageResults = this.lambdaQuery().setEntity(page.getQuery()).page(page);
        List<DictEntity> records = pageResults.getRecords();
        if (!records.isEmpty()) {
            final List<Long> rootIds = records.stream().map(r -> r.getId()).collect(Collectors.toList());
            final List<DictEntity> list = this.list(Wrappers.lambdaQuery(DictEntity.class).in(DictEntity::getParentId, rootIds));
            if (!list.isEmpty()) {
                for (DictEntity record : records) {
                    final List<DictEntity> collect = list.stream().filter(l -> l.getParentId().equals(record.getId())).collect(Collectors.toList());
                    if (collect != null) {
                        record.setChildren(collect);
                    }
                }
            }
        }
        return R.ok().put("page", pageResults);
    }

    public R removeWithSub(List<Long> ids) {
        final List<Long> subIds = this.listObjs(
            Wrappers.lambdaQuery(DictEntity.class).in(DictEntity::getParentId, ids),
            id -> Long.parseLong(id.toString())
        );
        ids.addAll(subIds);
        this.removeByIds(ids);
        return R.ok();
    }
}

